package org.iogame.socket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.HashMap;

/**
 * @author lc
 * @since 2022/10/12
 */
public class DefaultWebSocketClient extends WebSocketClient {

    enum Status{
        //回调对于所属类的接口
        OPEN,CLOSE,ERROR,MESSAGE
    }
    private final HashMap<Status,SocketCallback> map = new HashMap<>();

    private DefaultWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    private DefaultWebSocketClient(URI serverUri, Draft protocolDraft) {
        super(serverUri, protocolDraft);
    }

    public static DefaultWebSocketClient newMe(String url){
        try {
            return new DefaultWebSocketClient(new URI(url), new Draft_6455());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 添加回调
     * @since 2022/10/12
     */
    public void addCallback(Status s,SocketCallback c){
        map.put(s, c);
    }

    @Override
    public void onOpen(ServerHandshake han) {
        if (map.get(Status.OPEN) instanceof Open v) {
            v.onOpen(han);
        }
    }

    @Override
    public void onMessage(String message) {
        // TODO 暂时不支持字符串回调
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        if (map.get(Status.MESSAGE) instanceof Message v) {
            v.onMessage(bytes);
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        if (map.get(Status.CLOSE) instanceof Close v) {
            v.onClose(code, reason, remote);
        }
    }

    @Override
    public void onError(Exception ex) {
        if (map.get(Status.ERROR) instanceof Error v) {
            v.onError(ex);
        }
    }


}

